<template>
  <div>
    <el-upload :multiple="false" :class="type == 2 || lengths >= internalLimit ? 'hide' : 'show'" :auto-upload="true"
      list-type="picture-card" :action="uploadFileUrl" :before-upload="handleBeforeUpload" :file-list="uploadList"
      :limit="limitData" :on-error="handleUploadError" :on-exceed="handleExceed" :on-success="handleUploadSuccess"
      :data="data" :headers="headers" preview-teleported="true" ref="fileUpload">
      <i slot="default" class="el-icon-plus"></i>
      <div slot="file" slot-scope="{file}">

        <img class="el-upload-list__item-thumbnail" :src="file.url" alt="">
        <span class="el-upload-list__item-actions">
          <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
            <i class="el-icon-zoom-in" style="font-size: 15px;"></i>
          </span>
          <span class="el-upload-list__item-delete" style="font-size: 15px;" @click="handleDownload(file)">
            <i class="el-icon-download"></i>
          </span>
          <span v-if="type != 2" class="el-upload-list__item-delete" @click="handleRemove(file)">
            <i class="el-icon-delete" style="font-size: 15px;"></i>
          </span>
        </span>
      </div>
    </el-upload>
    <el-dialog :visible.sync="dialogVisible" append-to-body>
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
    <el-dialog :visible.sync="dialogVisiblePdf" append-to-body>
      <pdf v-for="item in pageTotal" :src="pdfUrl" :key="item" :page="item"></pdf>
    </el-dialog>
    <div v-if="isShowTip" style="line-height: 20px;">
      <div v-if="type != 2" style="font-size: 12px;">
        <template> 大小不超过 <b style="color: #f56c6c;">{{ size == 0 ? fileSize : size }}MB</b> </template>
        <template v-if="fileType || type != 2 || !isShowTip"> 格式为 <b style="color: #f56c6c;">{{
      suffix.lenth == 0 ? fileType.join(" /") : suffix.join("/") }}</b> </template>
        <template> 上传个数不能超过 <b style="color: #f56c6c;">{{ internalLimit == 0 ? limitData : internalLimit }}个</b>
        </template>
      </div>

    </div>
  </div>
</template>

<script>
import { getToken } from "@/utils/auth";
import { queryFile, fileRemove } from "@/api/system/file";
import { selectUploadByCode } from "@/api/system/upload";
import { download } from "@/utils/request";
import pdf from 'vue-pdf'
import { doc } from "@/assets/images/pdf.png";
export default {
  name: "FileUpload",
  components: { pdf },
  props: {
    // 值
    value: [String, Object, Array],
    // 数量限制
    limit: {
      type: Number,
      default: 1,
    },
    // 大小限制(MB)
    fileSize: {
      type: Number,
      default: 50,
    },
    // 文件类型, 例如['png', 'jpg', 'jpeg']
    fileType: {
      type: Array,
      default: () => ["doc", "xls", "ppt", "txt", "pdf"],
    },
    // 是否显示提示
    isShowTip: {
      type: Boolean,
      default: true
    },
    businessCode: {
      type: String,
      default: ''
    },
    businessId: {
      type: String,
      default: ''
    },
    //类型 0新增 1修改 2查看
    type: {
      type: [String, Number],
      default: '0'
    },
    //备注
    content: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      pdfUrl: '',
      dialogImageUrlPdf: '',
      dialogVisiblePdf: false,
      pageTotal: null,
      lengths: 0,
      dialogImageUrl: '',
      dialogVisible: false,
      disabled: true,
      upload_btn: false,
      //文件信息
      dataFile: null,
      limitData: 1,
      internalLimit: this.limit,  // 新增内部变量
      sysUpload: {},
      number: 0,
      uploadList: [],
      baseUrl: process.env.VUE_APP_BASE_API,
      uploadFileUrl: process.env.VUE_APP_BASE_API + "/common/upload", // 上传文件服务器地址
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      types: ['png', 'jpg', 'svg', 'bmp', 'jpeg', 'gif'],
      data: {},
      fileList: [],
      //后端获取附件类型
      suffix: [],
      //后端获取附件大小
      size: 0,
    };
  },
  // watch: {
  //   value: {
  //     handler(val) {
  //       if (val) {
  //         let temp = 1;
  //         // 首先将值转为数组
  //         const list = Array.isArray(val) ? val : this.value.split(',');
  //         // 然后将数组转为对象数组
  //         this.fileList = list.map(item => {
  //           if (typeof item === "string") {
  //             item = { name: item, url: item };
  //           }
  //           item.uid = item.uid || new Date().getTime() + temp++;
  //           return item;
  //         });
  //       } else {
  //         //this.fileList = [];
  //         return [];
  //       }
  //     },
  //     deep: true,
  //     immediate: true
  //   }
  // },
  created() {
    this.files();
    if (this.type != 0) {
      this.queryFile()
    }
    this.data = { businessId: this.businessId, businessCode: this.businessCode, content: this.content }
  },
  computed: {

    // 是否显示提示
    showTip() {
      return this.isShowTip && (this.fileType || this.fileSize);
    },
  },
  methods: {
    // 上传前校检格式和大小
    handleBeforeUpload(file) {
      let type = this.suffix.length == 0 ? this.fileType : this.suffix
      // 校检文件类型
      if (type) {
        const fileName = file.name.split('.');
        const fileExt = fileName[fileName.length - 1].toLowerCase();
        const isTypeOk = type.indexOf(fileExt) >= 0;
        if (!isTypeOk) {
          this.$modal.msgError(`文件格式不正确, 请上传${type.join("/")}格式文件!`);
          return false;
        }
      }
      // 校检文件大小
      if (this.fileSize) {
        const isLt = file.size / 1024 / 1024 < this.fileSize;
        if (!isLt) {
          this.$modal.msgError(`上传文件大小不能超过 ${this.fileSize} MB!`);
          return false;
        }

      }
      this.$modal.loading("正在上传文件，请稍候...");
      this.number++;
      return true;
    },
    handleRemove(file) {
      this.handleDelete(file)
    },
    handlePictureCardPreview(file) {

      if (file.downloadUrl != null && file.downloadUrl != '' && (file.downloadUrl).indexOf('.pdf') !== -1) {
        this.handlePictureCardPreviewPdf(file.downloadUrl);
      } else {
        this.dialogImageUrl = file.url;
        this.dialogVisible = true;
      }
    },
    handlePictureCardPreviewPdf(url) {
      this.pdfUrl = pdf.createLoadingTask(url)
      // 获取页码
      this.pdfUrl.promise.then(pdf => this.pageTotal = pdf.numPages).catch(error => {
      })
      this.dialogImageUrlPdf = url;
      this.dialogVisiblePdf = true;
    },
    //下载
    handleDownload(file) {

      let params = {
        resource: file.downloadUrl
      }
      download("/common/download/resource", params, file.name);
    },
    //获取文件信息
    queryFile() {
      if (this.type != 0 && this.businessId != '') {
        queryFile(this.businessId, this.businessCode).then(response => {
          this.dataFile = response.data
          for (let index = 0; index < response.data.length; index++) {
            const element = response.data[index];
            this.list(element)
          }

          this.fileList = this.fileList.concat(this.uploadList);
          this.lengths = this.fileList.length

        });
      }

    },
    // 文件个数超出
    handleExceed() {
      this.none = true
      this.$modal.msgError(`上传文件数量不能超过 ${this.limit} 个!`);
    },
    // 上传失败
    handleUploadError(err) {
      this.$modal.msgError("上传文件失败，请重试");
      this.$modal.closeLoading()
    },
    // 上传成功回调
    handleUploadSuccess(res, file) {
      if (res.code === 200) {
        this.lengths = this.lengths + 1
        // this.lengths = this.suffix.length;
        this.list(res);
        //this.$emit('getFile', this.uploadList);
        this.$modal.closeLoading();
        this.uploadedSuccessfully();

      } else {
        this.number--;
        this.$modal.closeLoading();
        this.$modal.msgError(res.msg);
        this.$refs.fileUpload.handleRemove(file);
        this.uploadedSuccessfully();
      }
    },
    list(res) {
      if (res.fileName.toLowerCase().indexOf(".pdf") != -1) {
        this.uploadList.push({ name: res.newFileName, url: require('@/assets/images/pdf.png'), id: res.id, downloadUrl: res.url, businessId: this.businessId, businessCode: this.businessCode, fileHz: 1 });
      }
      else if (res.fileName.toLowerCase().indexOf(".doc") != -1 || res.fileName.toLowerCase().indexOf(".docx") != -1) {
        this.uploadList.push({ name: res.newFileName, url: require('@/assets/images/doc.png'), id: res.id, downloadUrl: res.url, businessId: this.businessId, businessCode: this.businessCode, fileHz: 1 });
      }
      else if (res.fileName.toLowerCase().indexOf(".txt") != -1) {
        this.uploadList.push({ name: res.newFileName, downloadUrl: res.url, id: res.id, url: require('@/assets/images/txt.png'), businessId: this.businessId, businessCode: this.businessCode, fileHz: 1 });
      }
      else if (res.fileName.toLowerCase().indexOf(".xlsx") != -1 || res.fileName.toLowerCase().indexOf(".xls") != -1) {
        this.uploadList.push({ name: res.newFileName, downloadUrl: res.url, id: res.id, url: require('@/assets/images/excel.png'), businessId: this.businessId, businessCode: this.businessCode, fileHz: 1 });
      }
      else if (res.fileName.toLowerCase().indexOf(".zip") != -1) {
        this.uploadList.push({ name: res.newFileName, downloadUrl: res.url, id: res.id, url: require('@/assets/images/zip.png'), businessId: this.businessId, businessCode: this.businessCode, fileHz: 1 });
      }
      else if (res.fileName.toLowerCase().indexOf(".rar") != -1) {
        this.uploadList.push({ name: res.newFileName, downloadUrl: res.url, id: res.id, url: require('@/assets/images/rar.png'), businessId: this.businessId, businessCode: this.businessCode, fileHz: 1 });
      } else if (res.fileName.toLowerCase().indexOf(".html") != -1) {
        this.uploadList.push({ name: res.newFileName, downloadUrl: res.url, id: res.id, url: require('@/assets/images/html.png'), businessId: this.businessId, businessCode: this.businessCode, fileHz: 1 });
      }
      else {
        this.uploadList.push({ name: res.newFileName, downloadUrl: res.url, id: res.id, url: res.url, businessId: this.businessId, businessCode: this.businessCode, fileHz: 0 });

      }
    },
    //获取附件上传信息
    files() {
      // if(this.type!=0){
      selectUploadByCode(this.businessCode).then(response => {
        this.limitData = this.internalLimit >= response.data.fileLimit ? this.internalLimit : response.data.fileLimit
        this.internalLimit = response.data.fileLimit
        this.sysUpload = response.data
        // this.size = response.data.fileMaxSize
        this.size=30;
        let type = response.data.type.replace(/,/g, "").substr(1, response.data.type.length);
        this.suffix = type.split(".")

      });
      // }

    },
    // 删除文件
    handleDelete(file) {
      let type = this.type
      this.$modal.confirm('是否确认删除附件？').then(function () {
        return fileRemove(file.id, type);
      }).then(() => {
        for (let index = 0; index < this.uploadList.length; index++) {
          const element = this.uploadList[index];
          if (element.id == file.id) {
            this.uploadList.splice(index, 1);
          }
        }
        this.$emit('change', this.uploadList);
        this.lengths = this.lengths - 1
        this.$refs.fileUpload.clearFiles();
        this.$modal.msgSuccess("删除成功");
      }).catch((e) => {
      });

    },
    // 上传结束处理
    uploadedSuccessfully() {
      if (this.number > 0 && this.uploadList.length === this.number) {
        this.number = 0;
        // this.$emit("input", this.listToString(this.fileList));
        this.$modal.closeLoading();
      }
    },
    // 获取文件名称
    getFileName(name) {
      if (name.lastIndexOf("/") > -1) {
        return name.slice(name.lastIndexOf("/") + 1);
      } else {
        return "";
      }
    },
    // 对象转成指定字符串分隔
    listToString(list, separator) {
      let strs = "";
      separator = separator || ",";
      for (let i in list) {
        strs += list[i].url + separator;
      }
      return strs != '' ? strs.substr(0, strs.length - 1) : '';
    }
  }
};
</script>
<style scoped lang="scss">
.hide {
  position: relative;
  float: left;
  padding-top: 5px;
  padding-left: 8px;

  ::v-deep {
    .el-upload--picture-card {
      display: none;
    }

    .el-upload-list__item {
      border: 0;
      border-radius: 0;
      margin: 0 30px 0 0;
    }

  }
}

::v-deep .el-upload {
  width: 50px !important;
  height: 50px !important;
}

::v-deep .el-upload--picture-card {
  line-height: 60px;
}

::v-deep .is-success {
  width: 50px !important;
  height: 50px !important;
}

.el-upload-list--picture-card .el-upload-list__item-actions span+span {
  margin-left: 1px;
}
</style>
